package com.msmall.community.diary.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.msmall.base.pager.PaginationSupport;
import com.msmall.base.service.impl.BaseManagerImpl;
import com.msmall.base.util.ConstantDB;
import com.msmall.base.util.Constants;
import com.msmall.community.album.model.Photo;
import com.msmall.community.album.model.Reply;
import com.msmall.community.bbs.util.BbsUtil;
import com.msmall.community.common.util.ContentUtil;
import com.msmall.community.common.util.FilterCharsUtil;
import com.msmall.community.diary.dao.DiaryDao;
import com.msmall.community.diary.model.Diary;
import com.msmall.community.diary.model.DiaryReply;
import com.msmall.community.diary.service.DiaryManager;
import com.msmall.community.diary.util.DiaryUtil;
import com.msmall.community.diary.vo.DiaryReplyVO;
import com.msmall.community.user.service.UserManager;

public class DiaryManagerImpl extends BaseManagerImpl implements DiaryManager {

	private static final Log logger = LogFactory.getLog(DiaryManagerImpl.class);
	
	private DiaryDao diaryDao;

	private UserManager userManager;
	
	/**
	 * 用户创建日记
	 */
	public Diary saveDiary(Diary diary, Long userid, String userAgentType) throws Exception{
		try{
			Date date = new Date();
			String content = diary.getContent();
			String[] urls = new String[]{};
			try {
				urls = DiaryUtil.writeDiayFile(content,userid, userAgentType);
			} catch (IOException e) {
				logger.error(e);
			}
			
			if(StringUtils.isEmpty(diary.getContentAbstract())){
				int size = BbsUtil.getContentAbstractChars();
				content = ContentUtil.escapeHtmlTags(content);
				if(content.length() > size){
					diary.setContentAbstract(content.substring(0, size));
				}else{
					diary.setContentAbstract(content);
				}
			}
			
			diary.setFilePath(urls[0]);
			diary.setFileName(urls[1]);
			diary.setFileExt(urls[2]);
			
			diary.setUserid(userid);
			diary.setCreateTime(date);
			diary.setLastModifyTime(date);
			
			diary.setClickAmount(0);
			diary.setReplyAmount(0);
			diary.setTopAmount(0);
			diary.setEnabled(ConstantDB.AVALIABLE);
			
			diary = (Diary) diaryDao.saveObject(diary);
			
			userManager.addDiaryAmount(userid);
			return diary;
		}catch(Exception e){
			log.error(e);
			throw e;
		}
	}
	
	/**
	 * 验证Diary TITLE
	 * @return 1:正常；2字符太少；3字符太多;4含有非法字符
	 */
	public int validateDiaryTitle(String title){
		int titleOK = DiaryUtil.checkDiaryTitleLength(title);
		if(titleOK == 2){
			return 2;
		}
		if(titleOK == 3){
			return 3;
		}
		boolean titleC = FilterCharsUtil.containsFilterChars(title);
		if(titleC){
			return 4;
		}
		return 1;
	}
	
	/**
	 * 验证Diary content
	 * @return 1:正常；2字符太少；3字符太多;4含有非法字符
	 */
	public int validateDiaryContent(String content){
		int titleOK = DiaryUtil.checkDiaryContentLength(content);
		if(titleOK == 2){
			return 2;
		}
		if(titleOK == 3){
			return 3;
		}
		boolean titleC = FilterCharsUtil.containsFilterChars(content);
		if(titleC){
			return 4;
		}
		return 1;
	}
	
	/**
	 * 删除日记
	 */
	public void removeDiary(Long albumid, Long userid) throws Exception{
		try{
		}catch(Exception e){
			log.error(e);
		}
	}
	
	/**
	 * 分页显示日记列表
	 */
	public void diaryList(PaginationSupport page, Long userid) throws Exception{
		try{
			page.setPageSize(DiaryUtil.DIARY_LIST_PAGESIZE_DEFAULT);
			String sql = " FROM Diary WHERE userid=" +userid;
			page.setQueryString(sql);
			page.setAutoCount(true);
			diaryDao.getPagination(page);
		}catch(Exception e){
			log.error(e);
		}
	}
	
	/**
	 * 通过id查找日记
	 */
	public Diary getDiaryByid(Long diaryid) throws Exception{
		try{
			Diary diary = (Diary) diaryDao.get(Diary.class, diaryid);
//			diary.setClickAmount(diary.getClickAmount() + 1);
//			diaryDao.saveObject(diary);
			return diary;
		}catch(Exception e){
			log.error(e);
			throw e;
		}
	}
	
	/**
	 * 通过id查找日记的前一张日记,按ID排序，如果是第一张，跳到最后一张
	 */
	public Diary getDiaryPreByid(Long diaryid) throws Exception{
		try{
			Diary p = diaryDao.getDiaryPreByid(diaryid);
			if(p != null){
				return p;
			}else{
				PaginationSupport page = new PaginationSupport();
				StringBuffer buffer = new StringBuffer();
				buffer.append("select a from Diary a")
				.append(" WHERE a.userid=(select b.userid FROM Diary b where b.diaryid=").append(diaryid)
				.append(") AND a.diaryid !=").append(diaryid)
				.append(" ORDER BY a.diaryid DESC");
				page.setQueryString(buffer.toString());
				page.setAutoCount(false);
				page.setPageSize(1);
				diaryDao.getPagination(page);
				List list = page.getItems();
				if(list != null && list.size() > 0)
					return (Diary) list.get(0);
				else
					return null;
			}
		}catch(Exception e){
			log.error(e);
			throw e;
		}
	}
	/**
	 * 通过id查找照片的后一日记,按ID排序，如果是最后一张，跳到第一张
	 */
	public Diary getDiaryNextByid(Long diaryid) throws Exception{
		try{
			Diary p = diaryDao.getDiaryNextByid(diaryid);
			if(p != null){
				return p;
			}else{
				PaginationSupport page = new PaginationSupport();
				StringBuffer buffer = new StringBuffer();
				buffer.append("select a from Diary a")
				.append(" WHERE a.userid=(select b.userid FROM Diary b where b.diaryid=").append(diaryid)
				.append(") AND a.diaryid !=").append(diaryid)
				.append(" ORDER BY a.diaryid ASC");
				page.setQueryString(buffer.toString());
				page.setAutoCount(false);
				page.setPageSize(1);
				diaryDao.getPagination(page);
				List list = page.getItems();
				if(list != null && list.size() >0){
					return (Diary) list.get(0);
				}else{
					return null;
				}
			}
		}catch(Exception e){
			log.error(e);
			throw e;
		}
	}
	/**
	 * 获得日记的所有评论.盖楼效果
	 */
	public List<DiaryReplyVO> getReplysByDiaryid(Long diaryid, Short enabled)throws Exception{
		List<DiaryReplyVO> rlt = new ArrayList<DiaryReplyVO>();
		List<DiaryReply> list = diaryDao.getReplysByDiaryid(diaryid);
		if(list != null && list.size() > 0){
			DiaryReply reply;
			DiaryReplyVO vo;
			DiaryReplyVO parentvo;
			Long parentid;
			Map<Long,DiaryReplyVO> mapvos = new HashMap<Long,DiaryReplyVO>();
			for(int i=0;i<list.size(); i++){
				reply = list.get(i);
				vo = new DiaryReplyVO();
				vo.setReply(reply);
				mapvos.put(reply.getReplyid(), vo);
			}
			for(int i=0;i<list.size(); i++){
				reply = list.get(i);
				vo = mapvos.get(reply.getReplyid());
				parentid = reply.getParentid();
				parentvo = mapvos.get(parentid);
				if(parentid != null && parentid >0){
					parentvo.setNext(vo);
				}else{
					rlt.add(vo);
				}
			}
			List<DiaryReplyVO> subs;
			DiaryReplyVO next;
			for(int i=0;i<rlt.size();i++){
				vo = rlt.get(i);
				next = vo.getNext();
				if(next != null){
					subs = new ArrayList<DiaryReplyVO>();
					vo.setSubs(subs);
					while(next != null){
						subs.add(next);
						next = next.getNext();
					}
				}
			}
		}
		return rlt;
	}
	
	/**
	 * 同时增加日记评论回答数量
	 */
	public DiaryReply saveDiaryReply(DiaryReply reply, Long userid, String uat) throws Exception{
		try{
			reply.setCreateTime(new Date());
			reply.setUserid(userid);
			reply.setEnabled(ConstantDB.AVALIABLE);
			reply.setSource(Constants.USER_AGENT_TYPE_WML.equalsIgnoreCase(uat)? ConstantDB.USER_AGENT_TYPE_WML :ConstantDB.USER_AGENT_TYPE_HTML);
			reply = (DiaryReply) diaryDao.saveObject(reply);
			
			Diary d = (Diary) diaryDao.get(Diary.class, reply.getDiaryid());
			d.setReplyAmount(d.getReplyAmount() + 1);
			diaryDao.saveObject(d);
			return reply;
		}catch(Exception e){
			log.debug(e);
			throw e;
		}
	}
	
	/**
	 * 验证Diary.reply content
	 * @return 1:正常；2字符太少；3字符太多;4含有非法字符
	 */
	public int validateReplyContent(String content){
		int titleOK = DiaryUtil.checkDiaryReplyLength(content);
		if(titleOK == 2){
			return 2;
		}
		if(titleOK == 3){
			return 3;
		}
		boolean titleC = FilterCharsUtil.containsFilterChars(content);
		if(titleC){
			return 4;
		}
		return 1;
	}
	
	public void setDiaryDao(DiaryDao diaryDao) {
		this.diaryDao = diaryDao;
	}
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
}
